import { ReactiveEffect } from "vue";
import { ITERATE_KEY, TrackOpTypes } from "../utils";
import { activeEffect, targetMap } from "./effect";

let shouldTrack = true

export function pauseTracking() { 
  shouldTrack = false
}

export function resumeTracking() { 
  shouldTrack = true
}

/**
 * 
 * @param target 
 * @param type 触发依赖收集的类型，包括GET、HAS、ITERATE
 * @param key 
 */
export function track(target: any, type: TrackOpTypes, key?: string | symbol) {
  if (!shouldTrack || !activeEffect) {
    return
  }

  let propMap = targetMap.get(target)
  if (!propMap) {
    targetMap.set(target, (propMap = new Map()))
  }
  if(type === TrackOpTypes.ITERATE) key = ITERATE_KEY
  let typeMap = propMap.get(key!)
  if (!typeMap) {
    propMap.set(key!, (typeMap = new Map()))
  }

  let depSet = typeMap.get(type)
  if (!depSet) {
    typeMap.set(type, (depSet = new Set()))
  }
  
  if (!depSet.has(activeEffect)) {
    depSet.add(activeEffect)
    activeEffect.deps.push(depSet) // 将集合存储到依赖数组中，用于清除依赖
  }
}